import sys
import os
import datetime

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from database import Database

class DormitoryCheckout:
    def __init__(self):
        self.db = Database()
    
    def checkout_dormitory(self, student_id):
        """
        学生退宿处理
        
        参数:
            student_id (str): 学生学号
        
        返回:
            bool: 退宿成功返回True，否则返回False
        """
        try:
            # 验证输入
            if not student_id:
                print("错误：学生学号必须提供")
                return False
            
            # 连接数据库
            self.db.connect()
            
            # 检查学生是否存在
            self.db.cursor.execute(
                "SELECT id, name, dormitory_id FROM student WHERE student_id = ?",
                (student_id,)
            )
            student = self.db.cursor.fetchone()
            if not student:
                print(f"错误：学号为 {student_id} 的学生不存在")
                self.db.close()
                return False
            
            student_db_id, student_name, dormitory_id = student
            
            # 检查学生是否已分配宿舍
            if not dormitory_id:
                print(f"错误：学生 {student_name} 尚未分配宿舍，无法退宿")
                self.db.close()
                return False
            
            # 获取宿舍信息
            self.db.cursor.execute(
                "SELECT building, room_number FROM dormitory WHERE id = ?",
                (dormitory_id,)
            )
            dormitory = self.db.cursor.fetchone()
            if not dormitory:
                print(f"错误：无法获取宿舍信息")
                self.db.close()
                return False
            
            building, room_number = dormitory
            
            # 更新分配记录状态为inactive
            self.db.cursor.execute(
                "UPDATE allocation SET status = 'inactive' WHERE student_id = ? AND dormitory_id = ? AND status = 'active'",
                (student_db_id, dormitory_id)
            )
            
            # 更新学生的宿舍ID为NULL
            self.db.cursor.execute(
                "UPDATE student SET dormitory_id = NULL WHERE id = ?",
                (student_db_id,)
            )
            
            # 减少宿舍当前人数
            self.db.cursor.execute(
                "UPDATE dormitory SET current_count = current_count - 1 WHERE id = ?",
                (dormitory_id,)
            )
            
            # 添加退宿记录（在allocation表中添加一条状态为checkout的记录）
            checkout_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            self.db.cursor.execute(
                "INSERT INTO allocation (student_id, dormitory_id, allocation_date, status) VALUES (?, ?, ?, ?)",
                (student_db_id, dormitory_id, checkout_date, 'checkout')
            )
            
            self.db.conn.commit()
            print(f"成功：学生 {student_name} 已从宿舍 {building}-{room_number} 退宿")
            return True
        except Exception as e:
            print(f"错误：退宿处理时发生错误 - {str(e)}")
            return False
        finally:
            self.db.close()
    
    def batch_checkout_dormitory(self, student_ids):
        """
        批量退宿处理
        
        参数:
            student_ids (list): 学生学号列表
        
        返回:
            tuple: (成功退宿数量, 总数量)
        """
        success_count = 0
        total_count = len(student_ids)
        
        for student_id in student_ids:
            if self.checkout_dormitory(student_id):
                success_count += 1
        
        return success_count, total_count

# 如果直接运行此文件，提供命令行界面
if __name__ == "__main__":
    checkout = DormitoryCheckout()
    
    print("===== 宿舍退宿处理 =====")
    print("1. 单个学生退宿")
    print("2. 批量学生退宿")
    
    choice = input("请选择操作 (1-2): ")
    
    if choice == '1':
        student_id = input("请输入学生学号: ")
        checkout.checkout_dormitory(student_id)
    
    elif choice == '2':
        print("\n批量退宿处理 (每行输入一个学生学号)")
        print("输入空行结束输入\n")
        
        student_ids = []
        while True:
            line = input("> ")
            if not line:
                break
            
            student_id = line.strip()
            if student_id:
                student_ids.append(student_id)
        
        if student_ids:
            success_count, total_count = checkout.batch_checkout_dormitory(student_ids)
            print(f"\n批量退宿完成：成功 {success_count}/{total_count}")
        else:
            print("没有输入任何学生学号")
    
    else:
        print("无效的选择")